const list1 = document.querySelector('.custom ul');
const list2 = document.querySelector('.tee1 ul');
const list3 = document.querySelector('.tee2 ul');
const button = document.querySelector('button');

// 存储最终结果
let result = '';

// 生成8长度的随机字符串
const randomCharts = () => {
  let string = "";
    let choices = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()";

    for (let i = 0; i < 8; i++) {
      string += choices.charAt(Math.floor(Math.random() * choices.length));
    }
  return string;
}

let interval = null;
const stream = new ReadableStream({
  start(controller) {
    interval = setInterval(() => {
      const str = randomCharts();

      controller.enqueue(str);

      const listItem = document.createElement('li');
      listItem.textContent = str;
      list1.appendChild(listItem);
    }, 1000);

    button.addEventListener('click', () => {
      clearInterval(interval);
      teeStream();
      controller.close();
    });
  },
  cancel() {
    clearInterval(interval);
  }
});

const teeStream = () => {
  /**
   * tee 方法也会锁定读取流
   */
  const teeBranch = stream.tee();
  readStream(teeBranch[0], list2);
  readStream(teeBranch[1], list3);
}

const readStream = (stream, list) => {
  const reader = stream.getReader();
  let charsReceived = 0;

  reader.read().then(function processText({ done, value }) {
    if (done) {
      console.log('stream complete');
      return;
    }

    charsReceived += value.length;
    const chunk = value;
    const listItem = document.createElement('li');
    listItem.textContent = 'Read ' + charsReceived + ' characters so far. Current chunk = ' + chunk;
    list.appendChild(listItem);

    return reader.read().then(processText);
  })
}